<?php

defined('SYSPATH') or die('Access error!');

class Controller_Shop_Ajax extends Controller
{

    public function __construct(Request $request)
    {
        parent::__construct($request);
        header('Content-Type', 'application/json');
        if (!Request::$is_ajax)
        {
            $this->request->redirect(Route::get('shop')->uri(array('action' => 'index')));
            return;
        }
    }

    public function action_category_sub()
    {
        $id = intval($_POST['id']);
        if ($id == 0)
        {
            exit;
        }
        $category_list_temp = Model_Category::factory('category')->get_category_list('parent_id=' . $id);
        $category_list = array();
        if (Arr::validate_arr($category_list_temp))
        {
            foreach ($category_list_temp as $key => $value)
            {
                if (isset($value['id']))
                {
                    $value['children'] = Model_Category::factory('category')->get_category_list('parent_id=' . $value['id']);
                }
                $category_list[] = $value;
            }
        }
        echo json_encode($category_list);
        exit;
    }

    //操作上下架
    public function action_operate_goods()
    {
        $id = intval(Arr::get($_POST, 'id'));
        $act = Arr::get($_POST, 'act', 'onsale');

        if (!Model::factory('shop_goods')->is_exist(array('id' => $id, 'user_id' => Session::instance()->get_detail('user', 'id'))))
        {
            echo '无权操作';
            exit;
        }

        if (!in_array($act, array('onsale', 'downsale')))
        {
            echo '操作有误';
            exit;
        }

        $is_onsale = 0;
        if ($act == 'onsale')
        {
            $is_onsale = 1;
        }
        elseif ($act == 'downsale')
        {
            $is_onsale = 0;
        }
        
        if(Model::factory('shop_goods')->update(array('is_onsale'=>$is_onsale,'is_delete'=>0),array('id'=>$id))){
            echo '操作成功';
            exit;
        }
    }

    //删除某个产品
    public function action_delete_goods()
    {
        $id = intval(Arr::get($_POST, 'id'));
        if (!Model::factory('shop_goods')->is_exist(array('id' => $id, 'user_id' => Session::instance()->get_detail('user', 'id'))))
        {
            echo '无权操作';
            exit;
        }
        $is_delete = Model::factory('shop_goods')->get_var(array('id' => $id), 'is_delete');


        if ($is_delete == 0)
        {
            Model::factory('shop_goods')->update(array('is_delete' => 1), array('id' => $id));
            echo '产品加入回收站';
            exit;
        }

        if ($is_delete == 1)
        {
            Model::factory('shop_goods')->update(array('is_delete' => 2), array('id' => $id));
            echo '删除成功';
            exit;
        }
    }

}